//
//  PlistTool.swift
//  QNN
//
//  Created by zhenyu on 17/3/28.
//  Copyright © 2017年 qianshengqian. All rights reserved.
//

import Foundation

class PlistTool {
  
  /**
   备份Plist
   
   - parameter name: Plist 文件名
   
   */
  class func backUp(name: String) {
    let pathURL = Bundle.main.bundleURL.appendingPathComponent(name)
    let array = NSMutableArray(contentsOf: pathURL)
    
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let fileName = path + "/\(name)"
    debugPrint("fileName === \(fileName)")
  
    
    let newArray = PlistTool.readArrayFrom(plist: name)
    guard newArray != nil else {
      array?.write(toFile: fileName, atomically: true)
      return
    }
  }
  
  /**
   写入Plist
   
   - parameter array: 数组
   - parameter toPlist: Plist文件名

   */
  class func write(array: Array<Any>, toPlist: String) {
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let fileName = path + "/\(toPlist)"
    let newArray = NSArray(array: array)
    newArray.write(toFile: fileName, atomically: true)
  }
  
  /**
   读取Plist
   
   - parameter toPlist: Plist文件名
   - return: 返回数组
   
   */
  class func readArrayFrom(plist: String) -> NSMutableArray? {
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let fileName = path + "/\(plist)"
    let data = NSMutableArray(contentsOfFile: fileName)
    debugPrint("read==== \(data)")
    return data
  }
  
  // TODO: - 存字典的
  class func write(dic: Dictionary<String, Any>) {
    
  }
}
